package com.lethelh.mgallery.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.lethelh.mgallery.entity.Painting;
import com.lethelh.mgallery.service.PaintingService;
import com.lethelh.mgallery.utils.PageModel;

/**
 * 后台管理功能Controller
 */
@WebServlet("/management")
public class ManagementController extends HttpServlet {
	private PaintingService paintingService = new PaintingService();
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ManagementController() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		String method = request.getParameter("method");
		if(method.equals("list")) {
			this.list(request,response);
		}else if(method.equals("delete")) {
			this.delete(request,response);
		}else if(method.equals("show_create")) {
			this.showCreatePage(request,response);
		}else if(method.equals("create")) {
			this.create(request, response);
		}else if(method.equals("show_update")) {
			this.showUpdatePage(request,response);
		}else if(method.equals("update")) {
			this.update(request,response);
		}
	}

	/**
	 * 删除油画数据
	 * @param request
	 * @param response
	 */
	private void delete(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		
		if(id != null) {
			paintingService.delete(Integer.parseInt(id));
			PrintWriter out = null;
			try {
				out = response.getWriter();
				out.print("{\"result\":\"ok\"}");
			} catch (IOException e) {
				out.print("{\"result\":\""+e.getMessage()+"\"}");
			}finally {
				out.flush();
				out.close();
			}
		}
	}

	/**
	   * 更新油画数据
	 * @param request
	 * @param response
	 */
	private void update(HttpServletRequest request, HttpServletResponse response) {
		// TODO 更新油画数据业务逻辑
		/**
		 * 接收更新后的文件可以参考新增方法中的代码（注意更新页面中表单增加了新的元素Id和isPreviewModified）
		 * 在文件上传的判断中，要先判断一下isPreviewModified的值，如果为1，再进行接收文件。
		 */
		//1.初始化FileUpload组件
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload sf = new ServletFileUpload(factory);
		//2.遍历所有的FileItem
		try {
			List<FileItem> formData = sf.parseRequest(request);
			Painting painting = new Painting();
			int flag = 0;
			for (FileItem fi : formData) {
				if(fi.isFormField() == true) {
					switch(fi.getFieldName()) {
					case "pname":
						painting.setPname(fi.getString("UTF-8"));
						break;
					case "category":
						painting.setCategory(Integer.parseInt(fi.getString("UTF-8")));
						break;	
					case "price":
						painting.setPrice(Integer.parseInt(fi.getString("UTF-8")));
						break;
					case "description":
						painting.setDescription(fi.getString("UTF-8"));
						break;
					case "id":
						painting.setId(Integer.parseInt(fi.getString("UTF-8")));
						break;
					case "isPreviewModified":
						flag = Integer.parseInt(fi.getString("UTF-8"));
					default:
						break;
					}
				}else {
					//TODO flag = 1时，进行文件接收上传
					if(flag == 1) {
						String path = request.getServletContext().getRealPath("/upload");
						String fileName = UUID.randomUUID().toString();
						String suffix = fi.getName().substring(fi.getName().lastIndexOf("."));
						fi.write(new File(path,fileName+suffix));
						painting.setPreview("/upload/"+fileName+suffix);
					}
				}
			}
			paintingService.update(painting,flag);
			response.sendRedirect("/management?method=list");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 显示更新页面
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void showUpdatePage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		Painting painting = paintingService.findById(Integer.parseInt(id));
		request.setAttribute("painting", painting);
		request.getRequestDispatcher("/WEB-INF/jsp/update.jsp").forward(request, response);
	}
	
	private void showCreatePage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/jsp/create.jsp").forward(request,response);
	}
	
	private void create(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//文件上传时的数据处理与标准表单完全不同
//		String pname = request.getParameter("pname");
//		System.out.println(pname);
		//1.初始化FileUpload组件
		FileItemFactory factory = new DiskFileItemFactory();
		/**
		 * FileItemFactory 用于将前端表单的数据转换为一个个FileItem对象
		 * ServletFileUpload 则是将FileUpload组件提供Java Web的Http请求解析
		 */
		ServletFileUpload sf = new ServletFileUpload(factory);
		//2.遍历所有的FileItem
		try {
			List<FileItem> formData = sf.parseRequest(request);
			Painting painting = new Painting();
			for(FileItem fi:formData) {
				if(fi.isFormField() == true) {
					System.out.println("普通输入项:"+fi.getFieldName()+":"+fi.getString("UTF-8"));
					switch(fi.getFieldName()) {
					case "pname":
						painting.setPname(fi.getString("UTF-8"));
						break;
					case "category":
						painting.setCategory(Integer.parseInt(fi.getString("UTF-8")));
						break;	
					case "price":
						painting.setPrice(Integer.parseInt(fi.getString("UTF-8")));
						break;
					case "description":
						painting.setDescription(fi.getString("UTF-8"));
						break;
					default:
						break;
					}
				}else {
					System.out.println("文件上传项:"+fi.getFieldName());
					//3.文件保存到服务器目录
					String path = request.getServletContext().getRealPath("/upload");
					System.out.println("上传文件目录:"+path);
					//String fileName = "test.jpg";
					String fileName = UUID.randomUUID().toString();
					String suffix = fi.getName().substring(fi.getName().lastIndexOf("."));
					fi.write(new File(path,fileName+suffix));
					painting.setPreview("/upload/"+fileName+suffix);
				}
			}
			paintingService.create(painting);//新增功能完整实现了
			response.sendRedirect("/management?method=list");//返回列表项
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	
	private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String p = request.getParameter("p");
		String r = request.getParameter("r");
		if(p==null) {
			p = "1";
		}
		if(r==null) {
			r = "6";
		}
		PageModel pageModel = paintingService.pagination(Integer.parseInt(p),Integer.parseInt(r));
		request.setAttribute("pageModel", pageModel);
		request.getRequestDispatcher("/WEB-INF/jsp/list.jsp").forward(request, response);
	}

}
